package com.github.defense.starter.common.plugin;

import com.github.defense.common.request.DefenseRequest;
import com.github.defense.common.response.DefenseResponse;
import com.github.defense.plugin.base.DefensePlugin;
import com.github.defense.plugin.base.DefensePluginChain;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Objects;

/**
 * 插件默认处理链
 * @Author: lettger
 * @Date: 2021/12/13 下午1:08
 */
@Slf4j
public class DefaultDefensePluginChain implements DefensePluginChain {

    private int index;

    private final List<DefensePlugin> plugins;

    public DefaultDefensePluginChain(List<DefensePlugin> plugins) {
        this.plugins = plugins;
    }

    @Override
    public DefenseResponse execute(DefenseRequest request) {
        if (Objects.nonNull(request)) {
            if (this.index < plugins.size()) {
                log.debug("***Defense Request:{}", request);
                DefensePlugin plugin = plugins.get(this.index++);
                boolean skip = plugin.skip(request);
                if (skip) {
                    return this.execute(request);
                }
                return plugin.execute(request, this);
            }
        }
        return null;
    }
}
